/***************************************************************************
 *   Copyright (C) 2007 by Grzegorz Latarowski, Maciej Gajewski            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


// Qt
#include <QSqlQuery>
#include <QSqlRecord>

#include <QDebug>

// gcommons
#include "gexception.h"

// gparams
#include "gparams.h"

// libautonet
#include "autopackets.h"

// local
#include "baseserver.h"
#include "globaldata.h"


// ----------------- BaseServer::BaseServer() ----------------------------
BaseServer::BaseServer( QObject * pParent )
	: GNetServer( pParent )
{
		// register packets types used by autonet
	GAutoPacket::registerPackets();
}
// ---------------------------------------------------------------------------


// ------------------ BaseServer::processPacket() --------------------------
void BaseServer::processPacket( GNetPacket * pPacket )
{
	if ( pPacket )
	{
		switch ( pPacket->packetType() )
		{
			// request
			case GAutoPacket::PACKET_REQUEST:
				processRequest( qobject_cast< GAutoRequest * >( pPacket ) );
				break;

			// ignore others
			default:
				// nothing, only warn
				qWarning("Server::processPacket: unknown packet type: %d",
						 (int)pPacket->packetType() );
		}
	} // pAutoPacket
	else
	{
		qWarning("Server::processPacket: packet null or non GAutoPacket-derrived type");
		return; //maybe throw here?
	}
	
}
// ---------------------------------------------------------------------------


// -------------------- BaseServer::processRequest() -----------------------
void BaseServer::processRequest( GAutoRequest * pRequest )
{
	// check input.
	if ( ! pRequest )
	{
		return; // TODO maybe throw here
	}
	
	GNetPacketReply * pReply = NULL;
	try
	{

		// handle various requests
		switch( pRequest->requestType() )
		{
			case GAutoRequest::REQUEST_EVENTS:
			{
					// create and send reply packet 
				GAutoReplyEvents * pReplyEvents;
				
				pReplyEvents = new GAutoReplyEvents( pRequest->requestId() );
				pReply = pReplyEvents;
				
				if ( pReplyEvents )
				{
					processRequestEvents( pReplyEvents );
				}
				else
				{
					throw GSysError( tr("Can not allocate packet" ) );
				}
			}
			break;
			
			default:
				qWarning("Server::processRequest: unknown request: %d",
						 pRequest->requestType()) ; // warn
		}
	}
	catch( const GException& e )
	{
		// TODO handle error
		qWarning( "Exception in Server::processRequest: %s",
				  qPrintable( e.getMessage() ) );
	}

	// send reply
	if ( pReply )
	{
		sendPacket( *pReply );
        delete pReply;
	}

}
// ---------------------------------------------------------------------------


// -------------------------- BaseServer::passUser() -------------------------
quint8 BaseServer::passUser( const QString & userName, const QString & password )
{
	qDebug() << "userName" << userName;
	qDebug() << "password" << password;
	
	return GNetPacketAuthorizationAnswer::STATUS_OK; // test
}
// ---------------------------------------------------------------------------


// ----------------- BaseServer::processRequestEvents() ----------------------
void BaseServer::processRequestEvents( GAutoReplyEvents * pReplyEvents )
{
		// check pointers 
	if( !pReplyEvents ) return;

		// lock base 
	GlobalData::instance()->setBaseLocked();
	
		// read events from data base 
	QSqlQuery query( "SELECT * FROM autostop_events" );
	
	QSqlRecord record = query.record();
	int idColumn          = record.indexOf( "id" );
	int typeColumn        = record.indexOf( "type" );
	int dateTimeColumn    = record.indexOf( "dateTime" );
	int messageColumn     = record.indexOf( "message" );
	int firstImageColumn  = record.indexOf( "firstImage" );
	int secondImageColumn = record.indexOf( "secondImage" );

	while( query.next() )
	{
		Event event;
		event.id          = query.value( idColumn ).toInt();
		event.type        = query.value( typeColumn ).toInt();
		event.dateTime    = query.value( dateTimeColumn ).toDateTime();
		event.message     = query.value( messageColumn ).toString();
		event.firstImage  = query.value( firstImageColumn ).toByteArray();
		event.secondImage = query.value( secondImageColumn ).toByteArray();
		
		pReplyEvents->addEvent( event );
	}
	
		// clear table
	qDebug() << "deleting" << query.exec( "DELETE FROM autostop_events" );
	
		// clear query
	query.clear();
	
		// unlock base
	GlobalData::instance()->setBaseUnlocked();
}
// ---------------------------------------------------------------------------






// eof
